package com.mjee.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mjee.app.domain.User;
import com.mtoolkit.page.Page;

@Controller
public class UserController extends AbstractController {
	
	@RequestMapping(value="/signup.htm", method=RequestMethod.GET)
	public String toSignup() {
		return "signup";
	}
	
	@RequestMapping(value="/signup", method=RequestMethod.POST)
	public String signup(User user) {
		userService.add(user);
		return "redirect:/user/" + user.getId();
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String toLogin() {
		return "login";
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(User user, ModelMap model) {
		User targetUser = userService.findUser(user.getName());
		if (targetUser != null && user.getPassword().equals(targetUser.getPassword())) {
			model.put("user", targetUser);
			return "user_info";
		} else {
			return "error";
		}
	}
	
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public String logout() {
		return null;
	}
	
	@RequestMapping(value="/user/{id}/edit", method=RequestMethod.GET)
	public String toEditUser(@PathVariable int id, ModelMap model) {
	    User targetUser = userService.find(id);
        if (targetUser == null) {
            //WebUtil.send404Error(response);
            return null;
        }
        
        targetUser.setId(id);
        model.put("user", targetUser);
        
	    return "user_edit";
	}
	
	@RequestMapping(value="/user/{id}", method=RequestMethod.PUT)
	public String editUser(@PathVariable int id, User user) {
	    user.setId(id);
	    userService.edit(user);
	    
		return "redirect:/user/" + id;
	}
	
	@RequestMapping(value="/user/{id}", method=RequestMethod.DELETE)
	public String removeUser(@PathVariable int id) {
		userService.remove(id);
		
		return "redirect:/user";
	}
	
	@RequestMapping(value="/user/{id}", method=RequestMethod.GET)
	public String showUser(@PathVariable int id, ModelMap model) {
		User targetUser = userService.find(id);
		if (targetUser == null) {
			//WebUtil.send404Error(response);
			return null;
		}
		
		targetUser.setId(id);
		model.put("user", targetUser);
		
		return "user_info";
	}
	
	@RequestMapping(value="/user", method=RequestMethod.GET)
	public String showUserList(Page<User> page, ModelMap model) {
		page = new Page<User>(1, 10);
		Page<User> pageResult = userService.queryUsers(page);
		model.put("pageResult", pageResult);
		
		return "user_list";
	}
	
}
